<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="AI智能导诊·流式版" 
      left-text="返回" 
      left-arrow 
      @click-left="onClickLeft"
      :border="false"
      class="medical-nav-bar"
    >
      <template #left>
        <van-icon name="arrow-left" size="18" />
        <span class="nav-left-text">返回</span>
      </template>
      <template #title>
        <view class="nav-title-content">
          <van-icon name="service" size="20" class="nav-icon" />
          <text class="nav-title">AI智能导诊·流式版</text>
        </view>
      </template>
    </van-nav-bar>
    <!-- 就诊卡选择区域 -->
    <view v-if="!selectedCard" class="card-selection-container">
      <van-notice-bar
        left-icon="volume-o"
        text="请选择您的就诊卡开始AI智能导诊服务（流式版）"
        mode="closeable"
        color="#1989fa"
        background="#ecf9ff"
        class="notice-bar"
      />
      
      <!-- 就诊卡列表 -->
      <van-list class="card-list">
        <van-cell-group inset>
          <van-card
            v-for="card in medicalCards" 
            :key="card.id"
            :thumb="cardIcon"
            :title="card.patientName"
            :desc="formatBirthday(card.patientBirth)"
            class="medical-card"
            @click="selectCard(card)"
          >
            <template #tags>
              <van-tag type="success" size="mini">本人</van-tag>
              <van-tag type="primary" size="mini">默认</van-tag>
            </template>
            <template #price>
              <van-button 
                type="primary" 
                size="small" 
                round
                @click="selectCard(card)"
              >
                选择此卡
              </van-button>
            </template>
            <template #footer>
              <view class="card-footer">
                <van-icon name="certificate" />电子健康卡 · 国家卫生健康委员会监制
              </view>
            </template>
          </van-card>
        </van-cell-group>
          <!-- 卡片顶部 -->
          <view class="card-header">
            <view class="card-left">
              <text class="card-icon">🏥</text>
              <text class="card-title">电子健康卡</text>
            </view>
            <view class="card-right">
              <text class="card-issuer">国家卫生健康委员会监制</text>
            </view>
          </view>
          
          <!-- 卡片中间 -->
          <view class="card-middle">
            <view class="card-info-left">
              <text class="patient-name">{{ card.patientName }}</text>
              <view class="card-tag self-tag">本人</view>
            </view>
            <view class="card-info-right">
              <view class="card-tag default-tag">默认</view>
            </view>
          </view>
          
          <!-- 卡片底部 -->
          <view class="card-bottom">
            <view class="card-number">{{ formatBirthday(card.patientBirth) }}</view>
            <view class="select-btn">
              <text>选择此卡</text>
              <text class="arrow-icon">→</text>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <van-empty
          v-if="medicalCards.length === 0 && !loadingCards"
          image="search"
          description="暂无就诊卡"
        >
          <van-button type="primary" size="small" @click="loadMedicalCards">刷新</van-button>
        </van-empty>

        <!-- 加载状态 -->
        <van-loading 
          v-if="loadingCards" 
          type="spinner" 
          size="24px" 
          class="loading-state"
        >
          正在加载就诊卡...
        </van-loading>
      </van-list>
    </view>

    <!-- 聊天消息列表 -->
    <scroll-view
      v-if="selectedCard"
      class="chat-messages"
      scroll-y
      :scroll-top="scrollTop"
      scroll-with-animation
    >
      <!-- 当前选中的就诊卡信息 -->
      <van-sticky>
        <van-cell-group>
          <van-cell
            :title="`当前就诊人：${selectedCard.patientName}`"
            is-link
            @click="changeCard"
            class="current-card-cell"
          >
            <template #icon>
              <van-icon name="user-circle-o" class="card-user-icon" />
            </template>
            <template #right-icon>
              <van-button type="primary" size="mini" plain>更换</van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </van-sticky>
      
      <view class="message-list">
        <!-- 消息项 -->
        <view
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <van-cell
            class="message-content"
            :class="message.type"
          >
            <template #icon v-if="message.type === 'ai'">
              <van-icon name="service" size="20" class="message-avatar" />
            </template>
            <template #icon v-else>
              <van-icon name="user-circle-o" size="20" class="message-avatar" />
            </template>
            <template #title>
              <view class="message-text">
                {{ message.content }}
                <!-- 流式响应中的消息显示正在输入状态 -->
                <van-loading 
                  v-if="message.isStreaming" 
                  type="spinner" 
                  size="12px" 
                  class="typing-indicator"
                />
              </view>
            </template>
            <template #label>
              <view class="message-time">{{ message.time }}</view>
            </template>
          </van-cell>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <van-sticky position="bottom" v-if="selectedCard">
      <view class="input-area">
        <van-cell-group>
          <van-field
            v-model="inputText"
            placeholder="请描述您的症状..."
            :disabled="isConnecting"
            type="textarea"
            autosize
            show-word-limit
            maxlength="200"
            @confirm="sendMessage"
            class="message-input-field"
          >
            <template #button>
              <van-button
                type="primary"
                size="small"
                :disabled="!inputText.trim() || isConnecting"
                @click="sendMessage"
                :loading="isConnecting"
                loading-text="发送中"
              >
                {{ isConnecting ? "发送中" : "发送" }}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>
      </view>
    </van-sticky>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { getPatientByUserId } from '@/api/patient';
import { useUserStore } from "@/stores";

interface Message {
  content: string;
  type: "user" | "ai";
  time: string;
  isStreaming?: boolean;
}

// 就诊卡接口定义
interface MedicalCard {
  id: number;
  patientName: string;
  patientBirth: string;
  patientGender: number;
  isDefault: boolean;
  isSelf: boolean;
}

const messages = ref<Message[]>([]);
const inputText = ref("");
const isConnecting = ref(false);
const scrollTop = ref(0);
const userId = ref("");
const threadId = ref("");
let eventSource: EventSource | null = null;

// 就诊卡相关状态
const selectedCard = ref<MedicalCard | null>(null);
const medicalCards = ref<MedicalCard[]>([]);
const loadingCards = ref(false);

// 卡片图标
const cardIcon = ref('https://img.yzcdn.cn/vant/cat.jpeg');

// 返回按钮点击事件
const onClickLeft = () => {
  uni.navigateBack();
};

// 初始化userStore
const userStore = useUserStore();

onLoad(() => {
  console.log("AI智能导诊页面（流式版本） onLoad");
  loadMedicalCards();
});

onUnload(() => {
  // 页面卸载时关闭SSE连接
  if (eventSource) {
    eventSource.close();
    eventSource = null;
  }
});

// 加载就诊卡数据
const loadMedicalCards = async () => {
  loadingCards.value = true;
  try {
    // 从userStore获取当前登录用户的ID
    const currentUserId = userStore.userInfo?.userId || userStore.userData?.user?.userId;
    
    if (!currentUserId) {
      uni.showToast({
        title: '用户未登录，请先登录',
        icon: 'none'
      });
      return;
    }
    
    console.log('获取就诊卡列表 - 用户ID:', currentUserId);
    
    // 调用API获取就诊卡列表
    const response = await getPatientByUserId(currentUserId.toString());
    
    if (response.code === 200 && response.data) {
      medicalCards.value = response.data.map((card: any) => ({
        id: parseInt(card.patientId),
        patientName: card.patientName,
        patientBirth: card.patientBirth,
        patientGender: card.patientGender,
        isDefault: true,
        isSelf: true
      }));
      
      console.log('加载就诊卡成功:', medicalCards.value);
    } else {
      console.warn('获取就诊卡失败:', response.msg);
      uni.showToast({
        title: response.msg || '获取就诊卡失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载就诊卡失败:', error);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
  } finally {
    loadingCards.value = false;
  }
};

// 格式化生日显示
const formatBirthday = (birthday: string) => {
  return `生日：${birthday}`;
};

// 选择就诊卡
const selectCard = (card: MedicalCard) => {
  selectedCard.value = card;
  // 使用就诊卡ID作为userId
  userId.value = card.id.toString();
  threadId.value = 'session_' + card.id.toString();
  
  console.log('选择就诊卡:', card);
  console.log('设置userId为:', userId.value);
  
  // 初始化聊天
  initChat();
};

// 更换就诊卡
const changeCard = () => {
  selectedCard.value = null;
  messages.value = [];
  userId.value = "";
  threadId.value = "";
  
  // 重新加载就诊卡
  loadMedicalCards();
};

// 初始化聊天
const initChat = () => {
  console.log("初始化AI智能导诊聊天");
  // 添加欢迎消息，包含就诊人信息
  addMessage(
    `您好，${selectedCard.value?.patientName}！我是AI智能导诊助手，请描述您的症状，我会为您推荐合适的科室。`,
    "ai"
  );
};

// 添加消息
const addMessage = (
  content: string,
  type: "user" | "ai",
  isStreaming: boolean = false
) => {
  const now = new Date();
  const time = `${now.getHours().toString().padStart(2, "0")}:${now
    .getMinutes()
    .toString()
    .padStart(2, "0")}`;

  messages.value.push({
    content,
    type,
    time,
    isStreaming,
  });

  nextTick(() => {
    scrollToBottom();
  });

  return messages.value.length - 1; // 返回消息索引
};

// 更新消息内容
const updateMessage = (
  index: number,
  content: string,
  isStreaming: boolean = false
) => {
  if (messages.value[index]) {
    messages.value[index].content = content;
    messages.value[index].isStreaming = isStreaming;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  scrollTop.value = scrollTop.value === 99999 ? 99998 : 99999;
};

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || isConnecting.value) {
    return;
  }

  const userMessage = inputText.value.trim();
  addMessage(userMessage, "user");
  inputText.value = "";
  isConnecting.value = true;

  try {
    await connectToStreamApi(userMessage);
  } catch (error) {
    console.error("连接流式API失败:", error);
    addMessage("网络连接异常，请检查网络后重试。", "ai");
  } finally {
    isConnecting.value = false;
  }
};

// 连接流式API
const connectToStreamApi = async (query: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 构建流式请求URL
    const params = new URLSearchParams({
      query,
      userId: userId.value,
      threadId: threadId.value,
      isNewSession: (messages.value.length <= 2).toString(), // 减去欢迎消息和用户消息
    });

    const streamUrl = `http://localhost:8080/diagnosis/chat/stream?${params.toString()}`;

    // 在小程序中使用WebSocket或长连接来模拟SSE
    // 由于小程序不支持EventSource，这里提供WebSocket的实现示例

    // 为了简化，先使用普通HTTP请求模拟流式响应
    simulateStreamResponse(query).then(resolve).catch(reject);
  });
};

// 模拟流式响应（在实际项目中应该使用WebSocket）
const simulateStreamResponse = async (query: string): Promise<void> => {
  // 添加一个流式响应的消息
  const messageIndex = addMessage("", "ai", true);

  try {
    // 调用普通API获取完整响应
    const response = await callNormalApi(query);

    if (response && response.response) {
      // 模拟逐字显示效果
      const fullText = response.response;
      let currentText = "";

      for (let i = 0; i < fullText.length; i++) {
        currentText += fullText[i];
        updateMessage(messageIndex, currentText, true);

        // 添加短暂延迟模拟打字效果
        await new Promise((resolve) => setTimeout(resolve, 50));
      }

      // 完成流式显示
      updateMessage(messageIndex, fullText, false);

      // 检查是否有最终科室推荐，支持跳转功能
      if (response.isCompleted && response.deptId) {
        await handleDepartmentRecommendation(response);
      }
    } else {
      updateMessage(
        messageIndex,
        "抱歉，系统暂时无法处理您的请求，请稍后重试。",
        false
      );
    }
  } catch (error) {
    updateMessage(messageIndex, "网络连接异常，请检查网络后重试。", false);
  }
};

// 处理科室推荐，支持跳转功能
const handleDepartmentRecommendation = async (responseData: any) => {
  const deptId = responseData.deptId;
  const recommendedDepartment = responseData.recommendedDepartment;

  // 记录推荐信息
  console.log("收到科室推荐:", {
    department: recommendedDepartment,
    deptId: deptId,
    urgency: responseData.urgency,
    confidence: responseData.confidence,
  });

  // 延迟3秒后显示跳转提示，给用户时间阅读推荐内容
  setTimeout(() => {
    if (deptId && deptId > 0) {
      uni.showModal({
        title: "科室推荐完成",
        content: `已为您推荐${recommendedDepartment}，是否立即前往预约挂号？`,
        confirmText: "立即预约",
        cancelText: "稍后查看",
        success: (res) => {
          if (res.confirm) {
            // 跳转到医生选择页面，携带科室ID和科室名称
            uni.navigateTo({
              url: `/pages/appointment/doctor-select?departmentId=${deptId}&departmentName=${encodeURIComponent(
                recommendedDepartment || ""
              )}`,
            });
          }
        },
      });
    } else {
      // 如果没有有效的科室ID，只显示推荐完成提示
      uni.showToast({
        title: "科室推荐完成",
        icon: "success",
        duration: 2000,
      });
    }
  }, 3000);
};

// 调用普通AI API
const callNormalApi = async (query: string): Promise<any> => {
  const requestData = {
    query,
    userId: userId.value,
    threadId: threadId.value,
    isNewSession: messages.value.length <= 2,
  };

  return new Promise((resolve, reject) => {
    (uni as any).request({
      url: "http://localhost:8080/diagnosis/chat",
      method: "POST",
      header: {
        "Content-Type": "application/json",
      },
      data: requestData,
      success: (response: any) => {
        if (response.statusCode === 200) {
          resolve(response.data);
        } else {
          reject(new Error(`请求失败: ${response.statusCode}`));
        }
      },
      fail: (error: any) => {
        console.error("AI接口调用异常:", error);
        reject(error);
      },
    });
  });
};
</script>

<style lang="scss">
// 医疗主题配色
$medical-primary: #1989fa;
$medical-secondary: #07c160;
$medical-warning: #ff976a;
$medical-danger: #ee0a24;
$medical-light: #f7f8fa;
$medical-bg: #ffffff;

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: $medical-light;
}

// 导航栏样式
.medical-nav-bar {
  background: linear-gradient(135deg, $medical-primary 0%, #1976d2 100%);
  
  .nav-title-content {
    display: flex;
    align-items: center;
    gap: 8rpx;
    
    .nav-icon {
      color: white;
    }
    
    .nav-title {
      color: white;
      font-weight: bold;
    }
  }
  
  .nav-left-text {
    color: white;
    margin-left: 8rpx;
  }
}

// 通知栏样式
.notice-bar {
  margin: 24rpx;
  border-radius: 16rpx;
}

// 卡片选择区域
.card-selection-container {
  flex: 1;
  padding: 0 24rpx;
  background: transparent;
}

.card-list {
  max-height: 70vh;
}

.medical-card {
  margin-bottom: 24rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(25, 137, 250, 0.1);
  
  .card-footer {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 24rpx;
    color: #969799;
    margin-top: 16rpx;
  }
}

// 加载状态
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx;
  color: $medical-primary;
}

// 聊天消息区域
.chat-messages {
  flex: 1;
  background: transparent;
}

// 当前卡片信息
.current-card-cell {
  margin: 16rpx 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.1);
  
  .card-user-icon {
    color: $medical-primary;
  }
}

.message-list {
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.message-item {
  &.user {
    .message-content {
      background: $medical-primary;
      color: white;
      border-radius: 24rpx 24rpx 8rpx 24rpx;
      margin-left: 80rpx;
      
      .message-avatar {
        color: white;
      }
    }
  }

  &.ai {
    .message-content {
      background: white;
      color: #323233;
      border-radius: 24rpx 24rpx 24rpx 8rpx;
      margin-right: 80rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      
      .message-avatar {
        color: $medical-primary;
      }
    }
  }
}

.message-content {
  border: none !important;
  border-radius: 24rpx;
  padding: 20rpx !important;
}

.message-text {
  font-size: 32rpx;
  line-height: 1.5;
  word-wrap: break-word;
}

.typing-indicator {
  margin-left: 16rpx;
  color: $medical-primary;
}

.message-time {
  font-size: 22rpx;
  color: #969799;
  margin-top: 8rpx;
}

// 输入区域
.input-area {
  background: white;
  border-top: 1rpx solid #ebedf0;
  padding: 24rpx;
}

.message-input-field {
  .van-cell {
    border-radius: 24rpx;
    background: $medical-light;
    
    &:focus-within {
      border-color: $medical-primary;
      background: white;
    }
  }
}

// 响应式适配
@media (max-width: 750px) {
  .message-list {
    padding: 16rpx;
  }
  
  .message-item {
    &.user .message-content {
      margin-left: 60rpx;
    }
    
    &.ai .message-content {
      margin-right: 60rpx;
    }
  }
}
</style>
